(function () {
	nsbase.views.menus = new MenuFunc();

	function MenuFunc () {
		var self = this;

		self.init = init;
		self.setCurrent = setCurrent;

		var menus = [{
				groupName:"功能",
				groupIcon:"function",
				menus:[{
					name:"收益",
					link:"/income",
					code:"income"
				}]
			}];

		var $menuContainer = $('#menuContainer');
		var utility = nsbase.utility,
		    cssClass = {
				closed:'closed',
				selected:'selected'
			};

		function init (jsonMenus) {
			initMenuBar(jsonMenus);
		}

		function setCurrent (menuClass) {
			$menuContainer.find('dd.'+ menuClass).addClass(cssClass.selected);
		}
		function initMenuBar (jsonMenus) {
			if(!jsonMenus || jsonMenus.length == 0){
				alert("菜单为空");
				return;
			}
			var itemTmpl = '<dd class="${code}">\
						      <a href="${link}">${name}</a>\
						    </dd>',
				groupTmpl = '<dl>\
							    <dt>\
							    	<i class="icons ${groupIcon}"></i>\
						      		<i class="icons switch"></i>\
						      		${groupName}\
							    </dt>\
							 </dl>';

			$menuContainer.html('');
			for (var i = 0; i < jsonMenus.length; i++) {
				var groupMenu = jsonMenus[i];
				var $groupEl = $(utility.tmplFormat(groupTmpl,groupMenu));
				$menuContainer.append($groupEl);
				if(!groupMenu.menus || groupMenu.menus.length == 0){
					continue;
				}
				for (var j = 0; j < groupMenu.menus.length; j++) {
					var menuItem = groupMenu.menus[j];
					var $itemEl = $(utility.tmplFormat(itemTmpl,menuItem));
					$groupEl.append($itemEl);
				};
			};

			$menuContainer.find('dl').click(function() {
				var $sender = $(this);
				var hasSelected = $sender.find('.' + cssClass.selected).length > 0;
				if($sender.hasClass(cssClass.closed)){
					$sender.removeClass(cssClass.closed);
					$sender.removeClass(cssClass.selected);
				} else {
					$sender.addClass(cssClass.closed);
					if (hasSelected) $sender.addClass(cssClass.selected);
				}
			});
		}
	}
	
})();